"""
Code generation and programming prompts for FastMCP
"""

from fastmcp import FastMCP, Context
from typing import List, Optional
from pydantic import Field


class CodingPrompts:
    """Code generation and programming prompts for FastMCP"""

    def __init__(self, mcp: FastMCP):
        """Initialize and register coding prompts with the FastMCP server"""
        self.mcp = mcp

    def register(self):
        """Register all coding and programming prompts"""
        self.mcp.prompt(
            name="generate_function",
            description="Generate a prompt for creating a specific function",
            tags={"coding", "function", "development"},
        )(self.generate_function)

        self.mcp.prompt(
            name="code_review",
            description="Generate a prompt for thorough code review",
            tags={"coding", "review", "quality"},
        )(self.code_review)

        self.mcp.prompt(
            name="debug_assistance",
            description="Generate a prompt for debugging help and error resolution",
            tags={"coding", "debugging", "troubleshooting"},
        )(self.debug_assistance)

        self.mcp.prompt(
            name="api_integration",
            description="Generate a prompt for API integration and implementation",
            tags={"coding", "api", "integration"},
        )(self.api_integration)

    def generate_function(
        self,
        language: str = Field(
            description="Programming language (e.g., Python, JavaScript, Java)"
        ),
        function_name: str = Field(description="Name of the function to create"),
        purpose: str = Field(description="What the function should do"),
        parameters: List[str] = Field(
            description="Function parameters and their types"
        ),
        return_type: str = Field(description="Expected return type"),
        requirements: List[str] = Field(
            default=[], description="Specific requirements or constraints"
        ),
    ) -> str:
        """Generate a prompt for function creation."""

        params_text = "\n".join(f"- {param}" for param in parameters)
        # Ensure requirements is a list, not a FieldInfo object
        req_list = requirements if isinstance(requirements, list) else []
        requirements_text = (
            "\n".join(f"- {req}" for req in req_list) if req_list else "None specified"
        )

        prompt = f"""Create a {language} function with the following specifications:

**Function Name**: `{function_name}`

**Purpose**: {purpose}

**Parameters**:
{params_text}

**Return Type**: {return_type}

**Requirements**:
{requirements_text}

**Please provide**:

1. **Complete Function Implementation**
   - Write the complete function with proper syntax
   - Include appropriate error handling
   - Add input validation where necessary

2. **Documentation**
   - Add clear docstring/comments explaining the function
   - Document parameters and return value
   - Include usage examples

3. **Test Cases**
   - Provide at least 3 test cases demonstrating different scenarios
   - Include edge cases and error conditions
   - Show expected outputs

4. **Best Practices**
   - Follow language-specific coding conventions
   - Use appropriate data structures and algorithms
   - Consider performance implications

5. **Usage Example**
   - Show how to call the function
   - Demonstrate integration with other code
   - Highlight any setup requirements

Make sure the code is production-ready, well-documented, and follows best practices for {language}."""

        return prompt

    async def code_review(
        self,
        ctx: Context,
        code_snippet: str = Field(description="The code to be reviewed"),
        language: str = Field(description="Programming language of the code"),
        review_focus: List[str] = Field(
            default=["functionality", "performance", "security", "maintainability"],
            description="Areas to focus on during review",
        ),
    ) -> str:
        """Generate a comprehensive code review prompt."""

        await ctx.info(f"Creating code review prompt for {language} code")

        # Ensure review_focus is a list, not a FieldInfo object
        focus_list = review_focus if isinstance(review_focus, list) else []
        focus_areas = "\n".join(f"- {area.title()}" for area in focus_list)

        prompt = f"""Please conduct a thorough code review for the following {language} code:

```{language.lower()}
{code_snippet}
```

**Review Focus Areas**:
{focus_areas}

**Review Framework**:

1. **Functionality Review**
   - Does the code work as intended?
   - Are there any logical errors or bugs?
   - Does it handle edge cases properly?
   - Are there any missing features or incomplete implementations?

2. **Code Quality Assessment**
   - Is the code readable and well-structured?
   - Are variable and function names descriptive?
   - Is the code properly formatted and consistent?
   - Are there appropriate comments and documentation?

3. **Performance Analysis**
   - Are there any performance bottlenecks?
   - Can the algorithm be optimized?
   - Are resources used efficiently?
   - Are there any memory leaks or inefficient operations?

4. **Security Evaluation**
   - Are there any security vulnerabilities?
   - Is input validation adequate?
   - Are there any injection attack vectors?
   - Is sensitive data handled securely?

5. **Maintainability Check**
   - Is the code modular and reusable?
   - How easy would it be to modify or extend?
   - Are dependencies minimized and well-managed?
   - Is error handling comprehensive?

6. **Best Practices Compliance**
   - Does the code follow {language} conventions?
   - Are design patterns used appropriately?
   - Is the code testable?
   - Are there any code smells?

**Please provide**:
- **Summary**: Overall assessment of code quality
- **Issues Found**: List of problems with severity levels
- **Suggestions**: Specific improvement recommendations
- **Refactored Code**: Improved version if significant changes are needed
- **Learning Points**: Key takeaways for the developer

Rate the overall code quality on a scale of 1-10 and justify your rating."""

        return prompt

    def debug_assistance(
        self,
        error_message: str = Field(
            description="The error message or exception received"
        ),
        problematic_code: str = Field(description="The code that's causing the issue"),
        language: str = Field(description="Programming language being used"),
        context: str = Field(description="What the code is supposed to do"),
        attempted_solutions: List[str] = Field(
            default=[], description="Solutions already tried"
        ),
    ) -> str:
        """Generate a debugging assistance prompt."""

        # Ensure attempted_solutions is a list, not a FieldInfo object
        solutions_list = (
            attempted_solutions if isinstance(attempted_solutions, list) else []
        )
        attempted_text = (
            "\n".join(f"- {solution}" for solution in solutions_list)
            if solutions_list
            else "None mentioned"
        )

        prompt = f"""Help debug the following {language} code issue:

**Error Message**:
```
{error_message}
```

**Problematic Code**:
```{language.lower()}
{problematic_code}
```

**Context**: {context}

**Solutions Already Tried**:
{attempted_text}

**Please provide debugging assistance following this structure**:

1. **Error Analysis**
   - Explain what the error message means
   - Identify the specific line or section causing the issue
   - Explain why this error occurs in this context

2. **Root Cause Investigation**
   - Trace through the code execution path
   - Identify the underlying cause of the problem
   - Explain any contributing factors

3. **Solution Options**
   - Provide multiple approaches to fix the issue
   - Rank solutions by effectiveness and complexity
   - Explain the pros and cons of each approach

4. **Fixed Code**
   - Provide the corrected code with clear annotations
   - Highlight the specific changes made
   - Ensure the fix addresses the root cause

5. **Prevention Strategies**
   - Suggest ways to prevent similar issues in the future
   - Recommend best practices and coding patterns
   - Propose testing strategies to catch such errors

6. **Testing Recommendations**
   - Suggest test cases to verify the fix works
   - Recommend regression tests
   - Provide debugging techniques for similar issues

**Additional considerations**:
- Ensure the solution is compatible with the existing codebase
- Consider performance implications of the fix
- Address any security concerns that might arise"""

        return prompt

    def api_integration(
        self,
        api_name: str = Field(description="Name of the API to integrate"),
        api_documentation: str = Field(
            description="Link or description of API documentation"
        ),
        use_case: str = Field(description="What you want to achieve with the API"),
        language: str = Field(description="Programming language for implementation"),
        authentication_type: str = Field(
            default="unknown", description="Type of authentication required"
        ),
    ) -> str:
        """Generate a prompt for API integration guidance."""

        prompt = f"""Help implement integration with the {api_name} API in {language}:

**API Information**:
- **Name**: {api_name}
- **Documentation**: {api_documentation}
- **Authentication**: {authentication_type}

**Use Case**: {use_case}

**Please provide a complete integration guide including**:

1. **Setup and Authentication**
   - How to set up API credentials
   - Authentication implementation
   - Required headers and configuration
   - Environment variable management

2. **Core Integration Code**
   - Create a client class or module for API interaction
   - Implement key API methods needed for the use case
   - Include proper error handling and retry logic
   - Add request/response logging

3. **Data Models**
   - Define data structures for API requests and responses
   - Include data validation and serialization
   - Handle type conversions if necessary

4. **Error Handling**
   - Implement comprehensive error handling
   - Handle rate limiting and timeout scenarios
   - Provide meaningful error messages
   - Include retry mechanisms where appropriate

5. **Usage Examples**
   - Show how to use the integration in real scenarios
   - Provide multiple use case examples
   - Include both synchronous and asynchronous patterns if applicable

6. **Testing Strategy**
   - Unit tests for the integration
   - Mock API responses for testing
   - Integration tests with the actual API
   - Error scenario testing

7. **Best Practices**
   - Rate limiting and throttling
   - Caching strategies
   - Security considerations
   - Performance optimization tips

8. **Configuration Management**
   - Environment-specific configurations
   - Secrets management
   - Configuration validation

Please provide production-ready code with comprehensive documentation and examples."""

        return prompt
